package com.kichina.parking.module.message.socket.message;

import com.alibaba.fastjson.JSONObject;
import com.kichina.parking.exception.extend.JsonParseException;
import com.kichina.parking.module.message.socket.IMessageHandler;
import com.kichina.parking.module.message.socket.SocketStorageDeal;
import com.kichina.parking.module.message.socket.bean.BaseSocketResponse;
import com.kichina.parking.module.message.socket.enums.MessageTypeEnum;
import com.kichina.parking.module.message.socket.exception.MessageDealException;
import com.kichina.parking.upstream.Parking6OperatorInfoUpstreamHandler;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author Surging
 * @version 1.0
 * @ClassName SocketMessageCardTypeHandler
 * @date 2022-09-16 14:54
 * @desc 车场首次启用或操作员变化后上传操作员信息到服务端；
 */
@Component
@Order(Byte.MIN_VALUE + 7)
@Slf4j
public class OperatorInfoTypeHandler implements IMessageHandler {

    private final Parking6OperatorInfoUpstreamHandler parking6OperatorInfoUpstreamHandler;

    public OperatorInfoTypeHandler(Parking6OperatorInfoUpstreamHandler parking6OperatorInfoUpstreamHandler) {

        this.parking6OperatorInfoUpstreamHandler = parking6OperatorInfoUpstreamHandler;
    }

    @Override
    public void handler(JSONObject jsonObject, NetSocket netSocket) throws MessageDealException {
        // 保存车场操作员信息
        try {
            parking6OperatorInfoUpstreamHandler.recordParkingOperatorInfoUpstream(jsonObject);
        } catch (JsonParseException e) {
            if (Objects.nonNull(netSocket)) {
                SocketStorageDeal.sendResponse(netSocket, BaseSocketResponse.buildFailedNoOrderId(jsonObject.getString("service")));
            } else {
                throw new MessageDealException("保存车场操作员信息处理发生异常");
            }
        }
        if (Objects.nonNull(netSocket)) {
            SocketStorageDeal.sendResponse(netSocket, BaseSocketResponse.buildSuccessNoOrderId(jsonObject.getString("service")));
        }
    }

    @Override
    public boolean check(JSONObject jsonObject) {
        return MessageTypeEnum.UPLOAD_OPERATOR.getValue().equals(jsonObject.getString("service"));
    }

    @Override
    public boolean interrupt() {
        return true;
    }
}
